package com.gitee.neuray.security.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.gitee.neuray.security.auth.service.AuthService;
import com.gitee.neuray.security.auth.util.user.JwtAuthenticationRequest;
import com.gitee.neuray.security.auth.util.user.JwtAuthenticationResponse;
import com.gitee.neuray.security.auth.util.user.JwtWeAuthenticationResponse;
import com.gitee.neuray.security.common.msg.ObjectRestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author zhoyou
 */
@RestController
@RequestMapping("jwt")
@Slf4j
public class AuthController {
    @Value("${jwt.token-header}")
    private String tokenHeader;

    @Autowired
    private AuthService authService;

    @Value("${auth.user.defaultPassword}")
    private String defaultPassword;

    /**
     * @param authenticationRequest
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "token", method = RequestMethod.POST)
    @ResponseBody
    public ObjectRestResponse<?> createAuthenticationToken(
            @RequestBody JwtAuthenticationRequest authenticationRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
            Map<String,String> map = authService.login(authenticationRequest.getUsername(), authenticationRequest.getPassword(), request,response);
            String token = map.get("token");
            String name = map.get("name");
            String orgName = map.get("orgName");
            String position = map.get("position");
            String avatar = map.get("avatar");
            //String roles = map.get("roles");
        return new ObjectRestResponse().data(new JwtWeAuthenticationResponse(token,name,avatar,orgName,position)).msg("获取token成功");
    }

    /**
     * 在用户注销时清除token
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<?> removeAuthenticationToken(HttpServletRequest request) throws Exception {
        return new ObjectRestResponse().data("").msg("注销成功").rel(true);
    }

    @RequestMapping(value = "verify", method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<?> verify(String token) throws Exception {
        authService.validate(token);
        return new ObjectRestResponse<>().rel(true);
    }
}
